/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package encaps.action;

import encaps.entities.Grant;
import encaps.entities.UserLocal;
import encaps.entities.UserLocalHome;
import java.util.Map;
import javax.ejb.FinderException;
import javax.naming.*;


public class AuthorizationAction extends Action {

    private String login;
    private String password;

    public AuthorizationAction(Map parameters, Grant requiredGrant) {
        login = ((String[]) parameters.get("login"))[0];
        password = ((String[]) parameters.get("password"))[0];
    }

    public String execute() throws ActionExecutionException {
        try {
            Context ctx = new InitialContext();
            UserLocalHome userHome = (UserLocalHome) ctx.lookup("java:comp/env/ejb/User");
            UserLocal user = userHome.findByLogin(login);

            if(!user.getPassword().equals(password)) {
                throw new ActionExecutionException("Wrong password");
            }

            StringBuilder sb = new StringBuilder();
            sb.append("<h3>Profile of ");
            sb.append(user.getLogin());
            sb.append("</h3>");
            sb.append(user.getAvatar());
            sb.append("<br> <b>Info: </b>");
            sb.append(user.getInfo());
            sb.append("<br> <b>E-mail: </b>");
            sb.append(user.getEmail());
            sb.append("<br> <b>Contacts: </b>");
            sb.append(user.getContacts());
            sb.append("");
            sb.append("");
            return sb.toString();
        } catch(NamingException ex) {
            ex.printStackTrace();
            throw new ActionExecutionException(ex);
        } catch(FinderException ex) {
            //throw new ActionExecutionException("Wrong login");
            return "<h5>Wrong login!</h5>";
        }
    }

}
